package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    /**
     * 保存账户记录
     * 业务幂等性通过数据表中：用户ID设置唯一约束来保证
     *
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initAccount(Long userId) {
        //1.新增用户账户记录
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);

        BigDecimal giveAmount = new BigDecimal("10");
        userAccount.setTotalAmount(giveAmount);
        userAccount.setAvailableAmount(giveAmount);
        userAccount.setTotalIncomeAmount(giveAmount);
        userAccount.setLockAmount(new BigDecimal("0"));
        userAccount.setTotalPayAmount(new BigDecimal("0"));
        userAccountMapper.insert(userAccount);
        //2.新增账户变动日志
        this.saveUserAccountDetail(userId, "充值赠送：" + giveAmount, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, giveAmount, null);
    }

    @Override
    public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }


    /**
     * 获取当前登录用户账户可用余额
     *
     * @return
     */
    @Override
    public BigDecimal getAvailableAmount() {
        //1.获取当前用户ID
        Long userId = AuthContextHolder.getUserId();
        //2.根据用户ID查询账户记录
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getUserId, userId);
        UserAccount userAccount = userAccountMapper.selectOne(queryWrapper);
        Assert.notNull(userAccount, "用户{}账户不存在", userId);
        //3.返回可用余额
        return userAccount.getAvailableAmount();
    }


    /**
     * 用户余额支付订单-验证扣减账户余额
     *
     * @param accountDeductVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkAndDeduct(AccountDeductVo accountDeductVo) {
        //1.检查账户是否满足扣减需求，满足条件则完成账户扣减
        int count = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
        if (count == 0) {
            //抛出异常则进行全局事务回滚
            throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
        }
        //2.新增账户变动日志
        this.saveUserAccountDetail(accountDeductVo.getUserId(), accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(), accountDeductVo.getOrderNo());
    }
}
